//
//  ApplicationRenderer.cpp
//  Texture
//
//  Created by Yao Melo on 12/29/12.
//
//

#import <OpenGLES/EAGL.h>

//#include "Log.h"
#include <TargetConditionals.h>
#include <Availability.h>
#include "App.h"
#include "Mathematics.h"
#include "GraphicsDevice.h"
#include "MemoryManager.h"
#include "UI.h"
#include "Macros.h"
#include "Timing.h"
#include "Pathes.h"
#include "ResourceFile.h"
#include "Simulation.h"
#include "GL20Renderer.h"

#define INVADER_ANGULAR_VELOCITY 90.0

Simulation *simulation;
GL20Renderer *renderer;
NSTimeInterval lastUpdate;
float invaderAngle;

bool CShell::InitApplication()
{	
		return true;
}

bool CShell::UpdateScene()
{
    if(!simulation)
    {
        simulation = new Simulation();
        simulation->speedMultiplier = 1.1f;
    }
    if(!renderer)
    {
        renderer = [[GL20Renderer alloc] init];
    }

    float delta;
    NSTimeInterval now = [[NSDate date] timeIntervalSince1970];
    if(lastUpdate == 0)
    {
        delta = 0;
        lastUpdate = now;
    }
    else
    {
        delta = (float) (now - lastUpdate);
        lastUpdate = now;
    }
    simulation -> Update(delta);
    invaderAngle += delta*INVADER_ANGULAR_VELOCITY;
    while(invaderAngle>360.0f)
    {
        invaderAngle -=360.0f;
    }
    return true;
}

void printErr(int line)
{
    GLenum error = glGetError();
    NSLog(@"error %x,at line:%d",error,line);

}



bool CShell::RenderScene()
{


    glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
    if (simulation->gameState == eStateGameover) {
        [renderer loadGameoverTexture];
        [renderer renderGameoverWithWidth:320 height:480];

    }
    else if(simulation -> gameState == eStateWin)
    {
        [renderer loadGamewinTexture];
        [renderer renderGamewinWithWidth:320 height:480];
    }
    else
    {
        [renderer resetTextureForPlaying];
        [renderer renderBackgroundWithWidth:320 height:480];
        glEnable(GL_DEPTH_TEST);
        
        glEnable(GL_CULL_FACE);
        
        [renderer setCameraForShip:simulation->ship->position withWidth:320 height:480];
        [renderer renderShip:simulation->ship];
        [renderer renderInvaders:simulation->invaders withYAngle:(invaderAngle*PI)/180.0f];
        [renderer renderShots:simulation->shots];
        [renderer renderExplosions:simulation->explosions];
        glDisable(GL_DEPTH_TEST);
        glDisable(GL_CULL_FACE);
    }
    return true;
}


bool CShell::QuitApplication()
{
    delete simulation;
    simulation = NULL;
    [renderer release];
    renderer = nil;
    return true;
}